# Create your views here.
# -*- coding: utf-8 -*-
from django.views.generic.list_detail import object_list, object_detail
from wal.herramientas.models import Herramienta, HPrestamo
from wal.herramientas.forms import HerramientasForm, HPrestamosForm, HDevolucionForm
from wal.pedidos.forms import SearchForm
from django.template.context import RequestContext
from django.shortcuts import render_to_response
#from wal.views import update_object, create_object , delete_object
from django.views.generic.create_update import update_object, create_object , delete_object
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from wal.views import split_query_into_keywords
from django.db.models import Q

def obtenerHerramienta(request,object_id):
    if int(object_id):
        try:
            objectoHerramienta = Herramienta.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return 'No existe el objecto'
    else:
        return 'No existe el objecto'
    return objectoHerramienta

def listar(request,ot,o,page):
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Herramientas',request.path)])
    
    if ot=='asc':
        if int(o) == 1:
            orden = "-nombre"
        elif int(o) == 2:
            orden = "-descripcion"
        else:
            orden = "-nombre"
    elif ot=='desc':
        if int(o) == 1:
            orden = "nombre"
        elif int(o) == 2:
            orden = "descripcion"
        else:
            orden = "nombre"
    else:
        orden = "-nombre"
    if request.method == 'GET':
        form = SearchForm(request.GET)
        if form.is_valid():
            keywords = form.cleaned_data['keywords']
            keyword_list = split_query_into_keywords(keywords)
            herramientas = search_for_keywords(keyword_list)
            if herramientas:
                # Show the results
                qs = herramientas.order_by(orden)
            else:
                qs = Herramienta.objects.none()
            form = SearchForm()
            return object_list(request,
                   queryset = qs,
                   allow_empty = True,
                   template_name = 'herramientas/listar.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    else:
        form = SearchForm()
    return object_list(request,
                   queryset = Herramienta.objects.order_by(orden),
                   allow_empty = True,
                   template_name = 'herramientas/listar.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    
def ver(request, object_id):
    herramienta = obtenerHerramienta(request, object_id)
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Herramientas',reverse(listar,args=['asc',1,1])),(herramienta.nombre,request.path)])
    
    if herramienta == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    return render_to_response('herramientas/detalles.html', {'herramienta': herramienta}, context_instance=RequestContext(request))

def crear(request):
    request.breadcrumbs([('Depósito','/wal/dep'),('Herramientas',reverse(listar,args=['asc',1,1])),('Crear Herramienta',request.path)])
    return create_object(request,
                         model = Herramienta, 
                         form_class = HerramientasForm,
                         template_name = 'herramientas/herramienta.html', 
                         post_save_redirect = '/wal/herramientas/listar/ot=asc&o=1&page=1'
                         )

def editar(request, object_id):
    herramienta = obtenerHerramienta(request, object_id)
    if herramienta == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})

    request.breadcrumbs([('Depósito','/wal/dep'),('Herramientas',reverse(listar,args=['asc',1,1])),('Editar '+herramienta.nombre,request.path)])

    return update_object(request,
                        model = Herramienta, 
                        #form_class = PedidosForm,
                        template_name = 'herramientas/herramienta.html', 
                        post_save_redirect = '/wal/herramientas/ver/'+str(object_id),
                        object_id = object_id
                        )
    
def borrar(request, object_id,ot,o,page):
    herramienta = obtenerHerramienta(request, object_id)
    if herramienta == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    return delete_object(request,
                         model = Herramienta, 
                         template_name = 'herramientas/confirm_delete_herramienta.html', 
                         post_delete_redirect = reverse(listar, args=[ot,o,page]),
                         object_id = object_id
                         )
    
def search_for_keywords(keywords):
    """Make a search that contains all of the keywords."""
    herramientas = Herramienta.objects.all()
    for keyword in keywords:
        herramientas = herramientas.filter(
                                     Q(nombre__icontains=keyword)|
                                     Q(descripcion__icontains=keyword))
    return herramientas

def obtenerPrestamo(request,object_id):
    if int(object_id):
        try:
            objectoPrestamo = HPrestamo.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return 'No existe el objecto'
    else:
        return 'No existe el objecto'
    return objectoPrestamo

def search_for_keywords_prestamos(keywords):
    """Make a search that contains all of the keywords."""
    prestamos = HPrestamo.objects.all()
    for keyword in keywords:
        prestamos = prestamos.filter(
                                     Q(fecha__icontains=keyword)|
                                     Q(herramienta__nombre__icontains=keyword))
    return prestamos

def listarPrestamos(request,ot,o,page):
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Préstamos de Herramientas',request.path)])
    
    if ot=='asc':
        if int(o) == 1:
            orden = "-fecha"
        elif int(o) == 2:
            orden = "-herramienta"
        else:
            orden = "-fecha"
    elif ot=='desc':
        if int(o) == 1:
            orden = "fecha"
        elif int(o) == 2:
            orden = "herramienta"
        else:
            orden = "fecha"
    else:
        orden = "-fecha"
    if request.method == 'GET':
        form = SearchForm(request.GET)
        if form.is_valid():
            keywords = form.cleaned_data['keywords']
            keyword_list = split_query_into_keywords(keywords)
            prestamos = search_for_keywords_prestamos(keyword_list)
            if prestamos:
                # Show the results
                qs = prestamos.order_by(orden)
            else:
                qs = HPrestamo.objects.none()
            form = SearchForm()
            return object_list(request,
                   queryset = qs,
                   allow_empty = True,
                   template_name = 'herramientas/listarPrestamos.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    else:
        form = SearchForm()
    return object_list(request,
                   queryset = HPrestamo.objects.order_by(orden),
                   allow_empty = True,
                   template_name = 'herramientas/listarPrestamos.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )

def crearPrestamo(request):
    request.breadcrumbs([('Depósito','/wal/dep'),('Préstamo de Herramientas',reverse(listarPrestamos,args=['asc',1,1])),('Agregar Préstamo de Herramienta',request.path)])
    if request.method == "POST":
        cforms = HPrestamosForm(request.POST, instance=HPrestamo())
        if cforms.is_valid():
            new_prestamo = cforms.save()
            
        return HttpResponseRedirect('/wal/herramientas/prestamos/listar/ot=asc&o=1&page=1')
    else:
        cforms = HPrestamosForm(instance=HPrestamo())
    return render_to_response('herramientas/prestamo.html',{'form':cforms},context_instance=RequestContext(request))

    
def borrarPrestamo(request, object_id,ot,o,page):
    prestamo = obtenerPrestamo(request, object_id)
    if prestamo == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    return delete_object(request,
                         model = HPrestamo, 
                         template_name = 'herramientas/confirm_delete_prestamo.html', 
                         post_delete_redirect = reverse(listarPrestamos, args=[ot,o,page]),
                         object_id = object_id
                         )
def devolucion(request,object_id,ot,o,page):
    prestamo = obtenerPrestamo(request, object_id)
    if prestamo == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    request.breadcrumbs([('Depósito','/wal/dep'),('Préstamo de Herramientas',reverse(listarPrestamos,args=['asc',1,1])),('Devolución de Herramienta',request.path)])
    if request.method == "POST":
        cforms = HDevolucionForm(request.POST)
        if cforms.is_valid():
            cleaned_data = super(HDevolucionForm, cforms).clean()
            devolucion = cleaned_data.get('devolucion')
            devuelto = cleaned_data.get('devuelto')
            prestamo.devolucion = devolucion
            prestamo.devuelto = devuelto
            prestamo.save()
            return HttpResponseRedirect('/wal/herramientas/prestamos/listar/ot=asc&o=1&page=1')
    else:
        cforms = HDevolucionForm()
    return render_to_response('herramientas/devolucion.html',{'form':cforms},context_instance=RequestContext(request))
